package com.common.app.utls.pay

import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.PayResult
import com.common.app.data.bean.PayStatus
import com.common.app.data.bean.PayType
import com.common.app.data.bean.WXPayBean
import com.common.base.app.BaseApplication
import com.common.base.config.AppConfig
import com.common.base.utils.LogUtils
import com.common.base.utils.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory

object WXPayUtils {

    private var api: IWXAPI? = null

    private fun getIWXAPI(): IWXAPI {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(BaseApplication.getApplication(), null)
            api?.registerApp(AppConfig.WX_APP_ID)
        }
        return api!!
    }

    //调起微信支付
    fun pay(data: WXPayBean?) {
        if (!isWxAppInstalledAndSupported()){
            ToastUtils.showToast("请先安装微信或升级微信版本")
            LiveEventBus.get(KeyEvents.KEY_PAY_RESULT, PayResult::class.java).post(PayResult(PayType.WECHAT, PayStatus.FAILED))
            return
        }
        try {
            val req = PayReq()
            req.appId = data?.appid
            req.partnerId = data?.partnerid//Contants.MCHID
            req.prepayId = data?.prepayid
            req.nonceStr = data?.noncestr
            req.timeStamp = data?.timestamp
            req.packageValue = data?.paysign
            req.sign = data?.sign
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            if (api == null) {
                api = getIWXAPI()
            }
            api?.sendReq(req)
        } catch (e: Exception) {
            LogUtils.e("WXPayUtils", "异常：" + e.message)
        }
    }

    fun isWxAppInstalledAndSupported(): Boolean {
        return isWxInstalled() && getIWXAPI().wxAppSupportAPI >= Build.PAY_SUPPORTED_SDK_INT
    }

    fun isWxInstalled(): Boolean = getIWXAPI().isWXAppInstalled
}